/*
 *  WRMValidationAgent.java        22-ott-2009
 *   
 * Copyright (c) 2009 mentalsmash.org
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 *  The use of the Apache License does not indicate that this project is
 *  affiliated with the Apache Software Foundation.
 */

package org.mentalsmash.tazio.transactions.control.impl;

import java.util.List;

import org.mentalsmash.tazio.transactions.control.SystemTransactionManager;
import org.mentalsmash.tazio.transactions.control.TazioTransaction;
import org.mentalsmash.tazio.transactions.control.TransactionsLog;
import org.mentalsmash.tazio.transactions.control.ValidationAgent;

import com.google.common.collect.Sets;
import com.google.inject.Inject;

//TODO: check on the book if this validation agent may ever work
@Deprecated
class ForwardValidationAgent implements ValidationAgent {

    private final SystemTransactionManager tm;

    /**
     * Create a new instance of <tt>ForwardValidationAgent</tt> that will use
     * the provided {@link SystemTransactionManager}
     * 
     * @param tm
     *            the {@link SystemTransactinoManager} instance that manages
     *            transactions on the node were the <tt>ValidationAgent</tt>
     *            will operate
     */
    @Inject
    ForwardValidationAgent(final SystemTransactionManager tm) {
	this.tm = tm;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.impl.ValidationAgent#validate(org.
     * mentalsmash.tazio.transactions.Transaction)
     */
    @Override
    public boolean validate(final TazioTransaction tx) {
	final TransactionsLog txLog = this.tm.getTransactionsLog();
	final long initialSeqNo = tx.getSeqNo();

	// retrive running transactions that have started after this one
	final List<TazioTransaction> concurrentTxs = txLog.getActive(
		initialSeqNo, -1);

	// checking wheter the read set of concurrentTxs conflicts with the
	// write set of the validating one
	for (final TazioTransaction concurrent : concurrentTxs) {
	    // if the intersection is not empty
	    if (!Sets.intersection(tx.getWriteSet(), concurrent.getReadSet())
		    .isEmpty()) {
		return false;
	    }
	}

	return true;

    }

}
